﻿using System;
using System.ComponentModel;
using System.Globalization;

namespace Microsoft.Services.Clab.UI.Mvvmc
{
    public static class ExtensionMethods
    {
        public static string FormatEx(this string format, params object[] args)
        {
            return string.Format(CultureInfo.CurrentCulture, format, args);
        }

        public static void ExecuteWhen<T>(this T propertyChangedEnabledObject, Func<string, T, bool> propertyMatchEvaluator, Action<T> actionToExecute, bool executeOnce) where T : INotifyPropertyChanged
        {
            PropertyChangedEventHandler fn = null;
            fn = (s, e) =>
            {
                if (propertyMatchEvaluator(e.PropertyName, propertyChangedEnabledObject))
                {
                    actionToExecute(propertyChangedEnabledObject);

                    if (executeOnce)
                    {
                        propertyChangedEnabledObject.PropertyChanged -= fn;
                    }
                }
            };

            propertyChangedEnabledObject.PropertyChanged += fn;
        }

        public static T GetReference<T>(this WeakReference weakReference)
        {
            if (weakReference.IsAlive && weakReference is T)
            {
                return (T)weakReference.Target;
            }
            else
            {
                return default(T);
            }
        }
    }
}